import React, { useState, useEffect, useCallback } from 'react';
import { Table, Message } from '@hi-ui/hiui'
import { ListUser } from '../api/user'

// 类比：SpringBoot 的 @Service
// class UserService {
//     @PostConstruct
//     public void init() { /* 组件挂载时执行 */ }

//     @EventListener
//     public void onUserUpdate(UserEvent event) { /* 响应事件 */ }

//     @PreDestroy
//     public void cleanup() { /* 资源清理 */ }
// }

const UserManagement = () => {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(false);


    const loadUsers = useCallback(async () => {
        setLoading(true);
        try {
            // API 调用（类似 SpringBoot 的 RestTemplate）
            const response = await ListUser();
            console.log('API Response:', response); // 调试日志

            // 根据您的 API 响应结构调整
            let userData = [];
            if (response && response.data && Array.isArray(response.data)) {
                userData = response.data;
            } else if (Array.isArray(response)) {
                userData = response;
            } else {
                console.warn('Unexpected response format:', response);
                setUsers([]);
                return;
            }

            // 清理数据，确保所有字段都有默认值
            const cleanedData = userData.map(user => ({
                id: user.id ? Number(user.id) : 0,
                username: user.username ? String(user.username) : '',
                email: user.email ? String(user.email) : '',
                nickname: user.nickname ? String(user.nickname) : '',
                status: user.status ? String(user.status) : '0',
                createTime: user.createTime ? String(user.createTime) : '',
                updateTime: user.updateTime ? String(user.updateTime) : ''
            }));

            console.log('Cleaned data:', cleanedData);
            setUsers(cleanedData);
        } catch (error) {
            console.error('Load users error:', error);
            Message.open({
                title: "加载用户数据失败: " + (error.message || error),
                type: "error",
            });
            setUsers([]);
        } finally {
            setLoading(false);
        }
    }, []);

    // 类比：@PostConstruct - 组件挂载时执行一次
    useEffect(() => {
        console.log('UserManagement Component Mounted');
        loadUsers();

        // 类比：@PreDestroy - 清理函数
        return () => {
            console.log('UserManagement Component Unmounted');
            // 清理定时器、取消请求等
        };
    }, [loadUsers]); // 依赖 loadUsers 函数

    return (
        <div className="table-basic__wrap" style={{ minWidth: 660, background: "#fff", padding: '16px' }}>
            <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <h3 style={{ margin: 0 }}>用户管理</h3>
            </div>

            {loading ? (
                <div style={{ textAlign: 'center', padding: '40px' }}>
                    加载中...
                </div>
            ) : users.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                    暂无用户数据
                </div>
            ) : (
                <div style={{ width: '100%', overflow: 'hidden' }}>
                    <Table
                        fieldKey="id"
                        data={users.filter(user => user && typeof user === 'object')}
                        columns={[
                            {
                                title: 'ID',
                                dataKey: 'id',
                                width: 80,
                                render: (value) => String(value || '-')
                            },
                            {
                                title: '用户名',
                                dataKey: 'username',
                                width: 120,
                                render: (value) => String(value || '-')
                            },
                            {
                                title: '邮箱',
                                dataKey: 'email',
                                width: 200,
                                render: (value) => String(value || '-')
                            },
                            {
                                title: '昵称',
                                dataKey: 'nickname',
                                width: 120,
                                render: (value) => String(value || '-')
                            },
                            {
                                title: '状态',
                                dataKey: 'status',
                                width: 100,
                                render: (value) => {
                                    if (value === '1') return '启用';
                                    if (value === '0') return '禁用';
                                    return '-';
                                }
                            },
                            {
                                title: '创建时间',
                                dataKey: 'createTime',
                                width: 150,
                                render: (value) => String(value || '-')
                            },
                            {
                                title: '更新时间',
                                dataKey: 'updateTime',
                                width: 150,
                                render: (value) => String(value || '-')
                            }
                        ]}

                    />
                </div>
            )}
        </div>
    );
};

export default React.memo(UserManagement)